package com.iwhalecloud.bss.kite.cucc.order.listener;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.order.event.AfterOrderSaveEvent;
import com.iwhalecloud.bss.kite.dataservice.entity.OrderItem;
import com.iwhalecloud.bss.kite.dataservice.mapper.order.OrderItemMapper;
import com.iwhalecloud.bss.kite.order.client.dto.OrderContainer;
import com.iwhalecloud.bss.kite.order.client.dto.OrderRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class AfterOrderSaveListener {

    @Autowired
    private OrderItemMapper orderItemMapper;

    /**
     * Description: <br>
     * 订单保存后撤单订单项处理<br>
     * 更新原订单项单undo_flag标识
     * 
     * @taskId <br>
     * @param e <br>
     */
    @EventListener
    @Order(1)
    @Async
    public void dealWithdrawOrderItem(AfterOrderSaveEvent e) {
        OrderRequest orderRequest = e.getOrderRequest();
        // 获取订单项
        List<OrderItem> orderItems = OrderContainer.ofRequest(orderRequest).listOrderItems();

        for (OrderItem orderItem : orderItems) {
            // 非撤单不处理
            if (!KiteStringUtils.equals(KeyConsts.OPER_TYPE_EVT_C_0011_1200, orderItem.getOperType())) {
                continue;
            }

            // 更新撤单标识
            Example example = new Example(OrderItem.class);
            example.createCriteria().andEqualTo("orderItemId", orderItem.getOldOrderItemId()).andEqualTo("belongCustId",
                orderItem.getBelongCustId());
            OrderItem updOrderItem = new OrderItem();
            updOrderItem.setUndoFlag(orderItem.getUndoFlag());
            orderItemMapper.updateByExampleSelective(updOrderItem, example);
        }
    }

}
